﻿@using Citi.Scheduler.WebUi.Models
@model ScheduleModel
<script type="text/javascript">
    $(function () {
        
        if ($('#StartsOn').val() == '') {
            var myDate = new Date();
            var pickerDate =   myDate.getDate() + '/' + (myDate.getMonth() + 1) + '/' + myDate.getFullYear();
            $('#StartsOn').val(pickerDate);
        }

        $('#StartsOn, #EndsOn').datepicker({ dateFormat: 'dd/mm/yy'});

        @if (Model != null)
        {
            <text>$('#Periodicity').val('@(((int)Model.Periodicity).ToString())');</text>
            <text>$('#RepeatEvery').val('@Model.RepeatEvery.ToString()');</text>
            <text>$('#Sunday').prop('checked', @Model.RepeatTypes.Any(x => x.Weekday == (int)DayOfWeek.Sunday).ToString().ToLower());</text>
            <text>$('#Monday').prop('checked', @Model.RepeatTypes.Any(x => x.Weekday == (int)DayOfWeek.Monday).ToString().ToLower());</text>
            <text>$('#Tuesday').prop('checked', @Model.RepeatTypes.Any(x => x.Weekday == (int)DayOfWeek.Tuesday).ToString().ToLower());</text>
            <text>$('#Wednesday').prop('checked', @Model.RepeatTypes.Any(x => x.Weekday == (int)DayOfWeek.Wednesday).ToString().ToLower());</text>
            <text>$('#Thursday').prop('checked', @Model.RepeatTypes.Any(x => x.Weekday == (int)DayOfWeek.Thursday).ToString().ToLower());</text>
            <text>$('#Friday').prop('checked', @Model.RepeatTypes.Any(x => x.Weekday == (int)DayOfWeek.Friday).ToString().ToLower());</text>
            <text>$('#Saturday').prop('checked', @Model.RepeatTypes.Any(x => x.Weekday == (int)DayOfWeek.Saturday).ToString().ToLower());</text>
            <text>$('#DayMonth').prop('checked', @Model.RepeatTypes.Any(x => x.MonthType == 0).ToString().ToLower());</text>
            <text>$('#DayWeek').prop('checked', @Model.RepeatTypes.Any(x => x.MonthType == 1).ToString().ToLower());</text>
            <text>$('#typeAfter').prop('checked', @((Model.EndsAfter != null).ToString().ToLower()));</text>
            <text>$('#typeEndsOn').prop('checked', @((Model.EndsOn != null).ToString().ToLower()));</text>
            <text>$('#Time').val('@Model.Time.ToString("HH:mm")');</text>
            <text>$('#StartsOn').val('@Model.StartsOn.ToString("dd/MM/yyyy")');</text>

            if (Model.EndsOn.HasValue)
            {
                <text>$('#EndsOn').val('@Model.EndsOn.Value.ToString("dd/MM/yyyy")');</text>
            }
        }

        $('.time').mask('00:00');
        loadDescriptionRepeatEvery();
        fillDescriptionSchedule();

        $('#Periodicity').change(loadDescriptionRepeatEvery);

        $("#tableSchedule :input").change(fillDescriptionSchedule);

        $('input:radio[name=TypeEnds]').click(changeTypeEnds);
        changeTypeEnds();
    });

    function getWeekAndDay(date) {
        var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
        var prefixes = ['First', 'Second', 'Third', 'Fourth', 'Last'];

        return prefixes[0 | date.getDate() / 7] + ' ' + days[date.getDay()];
    }

    function changeTypeEnds() {
        var type = $('input:radio[name=TypeEnds]:checked')[0];
        var endsAfter = $("#EndsAfter");
        var endsOn = $("#EndsOn");

        endsAfter.attr('disabled', 'disabled');
        endsAfter.val('');
        endsAfter.numeric(false, function () { alert("Integers only"); this.value = ""; this.focus(); });
        endsOn.attr('disabled', 'disabled');
        endsOn.datepicker('destroy');
        endsOn.attr('readonly', true);

        if (type.id == 'typeAfter') {
            endsAfter.removeAttr('disabled');
            endsAfter.val('2');
        }
        else if (type.id == 'typeEndsOn') {
            endsOn.removeAttr('disabled');
            endsOn.datepicker({ minDate: 0,  dateFormat: 'dd/mm/yy' });
            var myDate = new Date();
            var pickerDate = myDate.getDate() + '/' + (myDate.getMonth() + 1) + '/' + myDate.getFullYear();
            endsOn.val(pickerDate);
        }

        fillDescriptionSchedule();
    }

    function fillDescriptionSchedule() {
        var periodicity = $('#Periodicity :selected').text();
        var repeatEvery = $("#RepeatEvery :selected").text();
        var hasRepeatEvery = $("#trRepeatEvery").is(":visible") && repeatEvery > 1;

        var description = hasRepeatEvery ? 'Every ' + repeatEvery : '';

        if (periodicity == '@Enums.Periodicity.Daily') {
            description += hasRepeatEvery ? ' days' : "Daily";
        } else if (periodicity == '@Enums.Periodicity.Weekly') {
            description += hasRepeatEvery ? ' weeks on ' : "Weekly on ";

            if ($("input:checkbox:checked.allDays").length == 7) {
                description += 'all days';
            } else if ($("input:checkbox:checked.businessDays").length == 5 && $("input:checkbox:checked.allDays").length == 5) {
                description += 'business days';
            } else {
                $("input:checkbox:checked.allDays").each(function (index, item) {
                    description += item.id + ', ';
                });
                description = description.substring(0, description.length - 2);
            }
        } else if (periodicity == '@Enums.Periodicity.Monthly') {
            description += hasRepeatEvery ? ' months on ' : "Monthly on ";

            if ($('#DayMonth')[0].checked) {
                description += 'day ' + $('#StartsOn').datepicker('getDate').getDate();
            } else {
                description += getWeekAndDay($('#StartsOn').datepicker('getDate'));
            }
        } else if (periodicity == '@Enums.Periodicity.Yearly') {
            description += hasRepeatEvery ? ' years' : "Yearly";
        } else if (periodicity == '@Enums.Periodicity.BusinessDay.GetDescription()') {
            description += 'Weekly on Business Days';
        } else if (periodicity == '@Enums.Periodicity.MondayWednesdayFriday.GetDescription()') {
            description += 'Weekly on Monday, Wednesday and Friday';
        } else if (periodicity == '@Enums.Periodicity.TuesdayThursday.GetDescription()') {
            description += 'Weekly on Tuesday and Thursday';
        }

        var type = $('input:radio[name=TypeEnds]:checked')[0];

        if (type.id == 'typeAfter') {
            description += ', ' + $("#EndsAfter").val() + ' times';
        }
        else if (type.id == 'typeEndsOn') {
            description += ' until ' + $("#EndsOn").val();
        }

        $("#descriptionSchedule").html(description);
    }

    function loadDescriptionRepeatEvery() {
        var periodicity = $('#Periodicity :selected').text();
        var descriptionRepeatEvery = $('#descriptionRepeatEvery');

        var trRepeatEvery = $("#trRepeatEvery");
        trRepeatEvery.show();
        var trRepeatOn = $("#trRepeatOn");
        trRepeatOn.hide();
        var trRepeatBy = $("#trRepeatBy");
        trRepeatBy.hide();

        if (periodicity == '@Enums.Periodicity.Daily') {
            descriptionRepeatEvery.html('days');
        } else if (periodicity == '@Enums.Periodicity.Weekly') {
            descriptionRepeatEvery.html('weeks');
            trRepeatOn.show();

            if ($("input:checkbox:checked.allDays").length == 0) {
                $("input:checkbox.allDays").each(function (index, item) { item.checked = true; });
            }
        } else if (periodicity == '@Enums.Periodicity.Monthly') {
            descriptionRepeatEvery.html('months');
            trRepeatBy.show();
        } else if (periodicity == '@Enums.Periodicity.Yearly') {
            descriptionRepeatEvery.html('years');
        } else {
            trRepeatEvery.hide();
            trRepeatOn.hide();
        }
    }

    function getRepeatOnOrRepeatBy() {
        var selectedRepeat = '';
        
        if ($('#trRepeatOn').is(':visible')) {
            $("input:checkbox:checked.allDays").each(function (index, item) { selectedRepeat += item.id + ','; });
            selectedRepeat = selectedRepeat.substring(0, selectedRepeat.length - 1);
        } else {
            selectedRepeat = $("input[type='radio'][name='RepeatBy']:checked").val();
        }

        return selectedRepeat;
    }
 
//    function save() {
//        $.ajax({
//            url: '@Url.Action("Save")',
//            data: $("#formSchedule").serialize(),
//            type: "post",
//            sucess: function (json) {
//                $('#hdnIdSaved').val(json.id);
//            }
//        });

//        return false;
//    }
</script>
@using (Html.BeginForm("Save", "Schedule", FormMethod.Post, new { id = "formSchedule" }))
{
    if (Model != null)
    {
    @Html.HiddenFor(model => model.Id)
    }
    
    <input type="hidden" id="hdnIdSaved" />
    
    <table id="tableSchedule" style="border-color: transparent !important; border-style: none !important;
        border-width: 0px !important;">
        <tr>
            <td>
                <span>Time:</span>
            </td>
            <td>
                @Html.TextBoxFor(model => model.Time, new { @class = "time", style = "width:70px" })
            </td>
        </tr>
        <tr>
            <td>
                <span>Repeats:</span>
            </td>
            <td>
                @Html.DropDownListFor(model => model.Periodicity, (IEnumerable<SelectListItem>)ViewBag.Periodicities)
            </td>
        </tr>
        <tr style="display: none;" id="trRepeatEvery">
            <td>
                <span>Repeat every:</span>
            </td>
            <td>
                @Html.DropDownListFor(model => model.RepeatEvery, (IEnumerable<SelectListItem>)ViewBag.RepeatEvery)&nbsp;
                <span id="descriptionRepeatEvery"></span>
            </td>
        </tr>
        <tr style="display: none;" id="trRepeatOn">
            <td>
                <span>Repeat on:</span>
            </td>
            <td>
                @Html.CheckBox("Sunday", new { @class = "allDays" }) S
                @Html.CheckBox("Monday", new { @class = "allDays businessDays" }) M
                @Html.CheckBox("Tuesday", new { @class = "allDays businessDays" }) T
                @Html.CheckBox("Wednesday", new { @class = "allDays businessDays" }) W
                @Html.CheckBox("Thursday", new { @class = "allDays businessDays" }) T
                @Html.CheckBox("Friday", new { @class = "allDays businessDays" }) F
                @Html.CheckBox("Saturday", new { @class = "allDays" }) S
            </td>
        </tr>
        <tr style="display: none;" id="trRepeatBy">
            <td>
                Repeat by
            </td>
            <td>@Html.RadioButton("RepeatBy", "DayMonth", true, new { id = "DayMonth" }) Day of
                the month
                @Html.RadioButton("RepeatBy", "DayWeek", new { id = "DayWeek" }) Day of the Week
            </td>
        </tr>
        <tr>
            <td>
                <span>Starts on:</span>
            </td>
            <td>
                @Html.TextBoxFor(model => model.StartsOn, new { style = "width:70px;", @class = "date" })
            </td>
        </tr>
        <tr>
            <td>
                <span>Ends:</span>
            </td>
            <td>
                <input type="radio" name="TypeEnds" checked="checked" id="typeNever" />Never<br />
                <input type="radio" id="typeAfter" name="TypeEnds" />After @Html.TextBoxFor(model => model.EndsAfter, new { style = "width:30px;", maxlength = "5" })
                occurences<br />
                <input type="radio" id="typeEndsOn" name="TypeEnds" />On @Html.TextBoxFor(model => model.EndsOn, new { style = "width:70px;", @class = "date" })
            </td>
            <tr>
                <td style="font-weight: bold; font-size: 13px;">
                    Summary
                </td>
                <td>
                    <span id="descriptionSchedule" style="font-weight: bold; font-size: 13px;"></span>
                </td>
            </tr>
        </tr>
    </table>
}